import React from 'react';
import { IRouteComponentProps, RequestConfig, history } from "umi";
import { message, Modal } from 'antd'
// 引入mobx的provider
import StoreContext from '@/context/storeContext'
// 引入mobx的根实例
import store from '@/store'
import { getCookie, removeCookie, setCookie } from '@/utils/bauch';
import Cookies from 'js-cookie';

let isModal = false;
const baseURL = 'http://111.203.59.61:8060/dev-api';
const errorCode = {
  '400': 'Bad Request',
  '401': 'Unauthorized',
  '403': 'Forbidden',
  '404': 'Not Found',
  '500': 'Internal Server Error',
  '502': "Bad GetWay",
  '503': 'Service Unavailable'
}
// setCookie(authorization);
export const request: RequestConfig = {
  timeout: 100000,
  errorConfig: {},
  middlewares: [],
  // 请求拦截器
  requestInterceptors: [(url, options) => {
    const authorization = getCookie() as string;
    console.log(url)
    if (!/http/.test(url)) {
      url = baseURL + url;
    }
    let headers = options.headers;
    if (authorization) {
      headers = { ...headers, authorization }
    }
    return {
      url,
      options: { ...options, interceptors: true, headers },
    };
  }],
  // 响应拦截器
  responseInterceptors: [async (response, options) => {
    let data = { code: 200, msg: '' };
    try {
      data = await response.clone().json();
      // 处理网络错误
      if (response.status !== 200) {
        message.error(response.statusText);
        return response;
      }
      // 处理业务错误
      if (data.code === 401) {
        if (isModal) {
          return response;
        }
        isModal = true;
        Modal.warning({
          title: '系统提示',
          closable: true,
          content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
          okText: '重新登陆',
          cancelText: '取消',
          onOk: () => {
            history.replace('/login/login');
            isModal = false;
          }
        });
        // 处理业务错误

      } else if (data.code !== 200) {
        message.error(data.msg);
        return response;
      }
    } catch (e) {
      message.error(e.message);
      return response;
    }
    return response;
  }],
};

// 覆盖根组件，把mobx的store注入
export function rootContainer(container: React.ReactElement) {
  return React.createElement(StoreContext.Provider, { value: store }, container);
}

// 导航守卫
const whiteList = ['/login', '/403', '/404'];
export function onRouteChange({ location, matchedRoutes }: any) {
  const authorization = getCookie() as string;
  if (matchedRoutes.length) {
    document.title = matchedRoutes[matchedRoutes.length - 1].route.title || '';
  }
  // 登陆态拦截
  if (!authorization) {
    if (whiteList.indexOf(location.pathname) == -1) {
      history.replace(`/login/login?redirect=${encodeURIComponent(location.pathname)}`)
    }
  }
  // 把首页重定向到/teachers/postSkill
  // if (location.pathname === '/') {
  //   history.replace('/student/studentSkill')
  // }
}